import React, {useEffect, useState} from 'react';
import {
    Box,
    Button,
    Card,
    CardContent,
    CardHeader,
    FormControl,
    IconButton, InputAdornment,
    InputLabel,
    MenuItem,
    Paper,
    Select, Stack,
    Switch,
    Table,
    TableBody,
    TableCell,
    TableContainer,
    TableHead,
    TableRow,
    Tooltip, Typography,
} from "@mui/material";
import EditIcon from '@mui/icons-material/Edit';
import LoadingButton from "@mui/lab/LoadingButton";
import DescriptionIcon from '@mui/icons-material/Description';
import CircularProgress from "@mui/material/CircularProgress";

import {list, save, visible} from "../../api/info/course";
import {list as listTeachers} from "../../api/info/teacher";

import {alert} from "../common/alert";
import {isPositiveInteger} from "../../utils/math";
import {SmallText} from "../common/my-text";
import store from "../../redux/store";
import {Done, RestartAlt} from "@mui/icons-material";
import RichTextEditor from "../common/quill-rte";

import {confirm} from "../common/confirm";

function Course() {

    const user = store.getState().auth?.user;

    const [entityId, setEntityId] = useState(0);
    const [title, setTitle] = useState('');

    const [teachers, setTeachers] = useState([]);
    const [courses, setCourses] = useState([]);

    const [course, setCourse] = useState({});

    const [loading, setLoading] = useState(false);
    const [submitting, setSubmitting] = useState(false);

    useEffect(() => {
        loadCourses();
        loadTeachers();
    }, []);

    function loadCourses() {
        setLoading(true);
        list().then(data => {
            setCourses(data);
            setLoading(false);
        });
    }

    function loadTeachers() {
        listTeachers().then(data => {
            setTeachers(data);
        });
    }

    function handleInputChange(event) {
        const {name, value} = event.target;
        setCourse({...course, [name]: value});
    }

    async function toggleVisible(course) {
        confirm(`将要${course.visible ? "隐藏" : "显示"}课程 【${course.name}】，确定吗？`)
            .then(choice => choice && visible(course.id, !course.visible))
            .then(data => {
                if (data) {
                    setCourses(courses.map(e => (e.id === course.id) ? {...e, visible: !course.visible} : e));
                }
            });
    }

    async function handleSubmit(event) {
        event.preventDefault();

        if (!isPositiveInteger(course.lessonCount)) {
            alert("课时数必须为正整数", "error");
            return;
        }

        if (!isPositiveInteger(course.price)) {
            alert("课时单价必须为正整数", "error");
            return;
        }

        if (!isPositiveInteger(course.salary)) {
            alert("课时薪酬必须为正整数", "error");
            return;
        }

        if (!isPositiveInteger(course.showOrder)) {
            alert("显示顺序必须为正整数", "error");
            return;
        }

        setSubmitting(true);

        course.id = course.id || 0;
        course.schoolId = user.schoolId;
        course.visible = course.visible || true;

        const result = await save(course);

        setSubmitting(false);

        if (result) {
            setCourse({});
            loadCourses();
        }
    }

    return (<>
        {entityId > 0 &&
            <RichTextEditor cat={'COURSE'} entityId={entityId} title={title} back={(() => setEntityId(0))}/>}

        {entityId === 0 &&
            <Box p={4} display="flex" gap={4} alignItems="flex-start" flexWrap="wrap">
                <Card raised sx={{width: '50%', padding: 2, boxSizing: 'border-box', minWidth: '540px'}}>
                    <CardHeader title={
                        <Stack direction="row" alignItems="center" spacing={1}>
                            <Typography variant="h5">课程信息</Typography>
                            {loading && <CircularProgress color="inherit" size={24}/>}
                        </Stack>}/>
                    <CardContent>

                        <TableContainer component={Paper}>
                            <Table>
                                <TableHead>
                                    <TableRow>
                                        <TableCell width={'30px'}>序号</TableCell>
                                        <TableCell>名称</TableCell>
                                        <TableCell width={'60px'}>课时数</TableCell>
                                        <TableCell width={'60px'}>单价</TableCell>
                                        <TableCell width={'60px'}>薪酬</TableCell>
                                        <TableCell width={'140px'} align="center">操作</TableCell>
                                    </TableRow>
                                </TableHead>
                                <TableBody>
                                    {courses.map(e => (
                                        <TableRow key={e.id}>
                                            <TableCell component="th" scope="row">{e.showOrder}</TableCell>
                                            <TableCell>{e.name}</TableCell>
                                            <TableCell>{e.lessonCount}</TableCell>
                                            <TableCell>{e.price}</TableCell>
                                            <TableCell>{e.salary}</TableCell>
                                            <TableCell align="center">
                                                <Tooltip title={e.visible ? "显示" : "隐藏"}>
                                                    <Switch checked={e.visible}
                                                            onChange={() => toggleVisible(e)}/>
                                                </Tooltip>
                                                <IconButton onClick={() => setCourse(e)} size="small">
                                                    <EditIcon/>
                                                </IconButton>
                                                <IconButton onClick={() => {
                                                    setEntityId(e.id);
                                                    setTitle(e.name);
                                                }} size="small">
                                                    <DescriptionIcon/>
                                                </IconButton>
                                            </TableCell>
                                        </TableRow>
                                    ))}
                                </TableBody>
                            </Table>
                        </TableContainer>
                    </CardContent>
                </Card>

                <Card raised sx={{width: '40%', padding: 3, boxSizing: 'border-box', minWidth: '320px'}}>
                    <CardHeader title={course.id ? '修改' : '新增'}/>
                    <CardContent>
                        <Box>
                            <form onSubmit={handleSubmit}>

                                <SmallText label="课程名称" name="name" value={course.name} autoFocus={true}
                                           onChange={handleInputChange}/>

                                <FormControl fullWidth sx={{marginTop: "8px"}} required size="small">
                                    <InputLabel>授课老师</InputLabel>
                                    <Select label="授课老师" name="teacherId" value={course.teacherId || ''}
                                            onChange={handleInputChange}>
                                        {teachers.map(e => (
                                            <MenuItem key={e.id} value={e.id}>{e.name}</MenuItem>
                                        ))}
                                    </Select>
                                </FormControl>

                                <SmallText label="课时数" name="lessonCount" value={course.lessonCount}
                                           onChange={handleInputChange}/>
                                <SmallText label="课时单价" name="price" value={course.price}
                                           InputProps={{
                                               endAdornment: <InputAdornment position="end">分</InputAdornment>,
                                           }}
                                           onChange={handleInputChange}/>
                                <SmallText label="课时薪酬" name="salary" value={course.salary}
                                           InputProps={{
                                               endAdornment: <InputAdornment position="end">分</InputAdornment>,
                                           }}
                                           onChange={handleInputChange}/>
                                <SmallText label="显示顺序" name="showOrder" value={course.showOrder}
                                           onChange={handleInputChange}/>

                                <Button
                                    variant="contained"
                                    color="primary"
                                    startIcon={<RestartAlt/>}
                                    sx={{marginTop: "16px", mr: 2}}
                                    onClick={() => setCourse({})}
                                > 清空
                                </Button>

                                <LoadingButton
                                    type="submit"
                                    disabled={submitting}
                                    variant="contained"
                                    color="primary"
                                    startIcon={<Done/>}
                                    sx={{marginTop: "16px"}}
                                    loadingIndicator={<CircularProgress color="inherit" size={24}/>}
                                    loading={submitting}
                                >
                                    提交
                                </LoadingButton>
                            </form>
                        </Box>
                    </CardContent>
                </Card>
            </Box>}
    </>);
}

export default Course;
